package ru.ifmo.thesis.suite;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import ru.ifmo.thesis.domain.Job;
import ru.ifmo.thesis.domain.Worker;
import ru.ifmo.thesis.task.Task;
import ru.ifmo.thesis.task.TaskGenerationOptions;

import com.thoughtworks.xstream.XStream;

public class SuiteSerializer {
	
	private static final String TASK_SUITE_XML_NAME = "task-suite.xml";

	public static TaskSuite readZippedSuite(InputStream input) throws IOException {
		ZipInputStream inputStream = new ZipInputStream(input);
		ZipEntry nextEntry = inputStream.getNextEntry();
		if (!TASK_SUITE_XML_NAME.equals(nextEntry.getName())) {
			throw new RuntimeException("wrong file format");
		}
		
		TaskSuite suite = readSuite(inputStream);
		inputStream.close();
		return suite;
	}

	public static TaskSuite readSuite(InputStream input) {
		XStream stream = getStream();
		return (TaskSuite) stream.fromXML(input);
	}

	
	public static void writeZippedSuite(TaskSuite suite, OutputStream output) throws IOException {
		ZipOutputStream zip = new ZipOutputStream(output);
		zip.putNextEntry(new ZipEntry(TASK_SUITE_XML_NAME));
		SuiteSerializer.writeSuite(suite, zip);
		zip.close();
	}

	public static void writeSuite(TaskSuite t, OutputStream output) {
		XStream stream = getStream();
		stream.toXML(t, output);
	}

	private static XStream getStream() {
		XStream result = new XStream();
		result.alias("task", Task.class);
		result.alias("worker", Worker.class);
		result.alias("job", Job.class);
		result.alias("task-suite", TaskSuite.class);
		result.alias("generation-metadata", TaskGenerationOptions.class);
		return result;
	}
}
